// JavaScript Document
$(function(){
	//slide弹出层
	$('.slideBtn').each(function(){
		$(this).hover(function(){
			$(this).children('.slideBox').slideDown(300);
		}, function(){
			$(this).children('.slideBox').hide();
		})
	})
	
	//头部搜索
	$('.headSearch').hover(function(){
		$(this).css( 'background-color' , '#fff' );
		if( !$(this).children('input').is(":animated") ){
			$(this).children('input').animate({ 'width' : 100 }, 200);
		}
		$('.sClassify i').css({
			'filter' : 'alpha(opacity=100)',
			'opacity' : 1
			})
	}, function(){
		$(this).css( 'background-color' , '#1f2537' );
		$(this).children('input').animate({ 'width' : 40 }, 200);
		$('.sClassify i').css({
			'filter' : 'alpha(opacity=50)',
			'opacity' : 0.5
			})
	});
	
	//头部搜索动作
	$("#searchTab").find('li').click(function(){
		$("#currentTab").html($(this).html());
		var tab = $(this).attr('tab');
		$("#topSearchTab").val(tab);
	});
    //头部搜索调用栏目ID  
	$(function(){
	$("#searchTab li").click(function(){
		var type_id = $(this).attr("rel");
		$("#type_id").val(type_id);
		
    });
	
});
	
	//头部提醒
	$('.messageBox > dd:first').show();
	$('.messageBox .inboxDt > a').click(function(){
		index = $(this).index('.messageBox .inboxDt > a');
		$(this).addClass('current').siblings("a").removeClass('current');
		$('.messageBox > dd').eq(index).show().siblings('dd').hide();
	})
	//作品列表动画
	$('.workList').hover(function(){
		$(this).animate({
			'top' : -2,
			'box-shadow' : '0 2px 6px rgba(0,0,0,0.6)'
			},200)
	}, function(){
		$(this).animate({
			'top' : 0,
			'box-shadow' : '0 2px 3px rgba(0,0,0,0.06)'
			},200)
	})
	
	//textarea换行
	var element = $(".textareaContent");
    var temp =  element.text().replace(/\n/g, '<br />');
    element.html(temp);
	

	
	//赞动作
	$(".praiseBtn").click(function(){
		var ele = $(this);
		var tab = ele.attr('tab');
		var item_id = ele.attr('data');
		$.post('/Index/dopraise', {item_id:item_id, tab:tab}, function(result){
			if (result.status == 100) {
				ele.text(parseInt(ele.text()) + 1);
			} else if (result.status == 101) {
				jump(1, '/User/login?from=' + urlencode(window.document.location.pathname));
				putNotice(result.msg);
			} else {
				putNotice(result.msg);
			}
		}, 'json');
	});
	
	//收藏(取消)动作
	$(".favBtn").click(function(){
		var ele = $(this);
		var item_id = ele.attr('data');
		var tab = ele.attr('tab');
		$.post('/Index/dofav', {item_id:item_id, tab:tab}, function(result){
			putNotice(result.msg);
			if (result.status == 100) {
				ele.addClass('current').addClass('faved').find(".text").text('已收藏');
			} else if (result.status == 99) {
				ele.removeClass('current').removeClass('faved').find(".text").text('收藏');
			} else if (result.status == 101) {
				jump(1, '/User/login?from=' + urlencode(window.document.location.pathname));
			}
		}, 'json');
	}).hover(function(){
		if ($(this).hasClass('faved')) {
			$(this).find(".text").text('取消收藏');
		}
	},function(){
		if ($(this).hasClass('faved')) {
			$(this).addClass('current').find(".text").text('已收藏');
		} else {
			$(this).find(".text").text('收藏');
		}
    });
	
	//用户收藏列表页取消收藏动作
	$(".listFavBtn").click(function(){
		var ele = $(this);
		var item_id = ele.attr('data');
		var tab = ele.attr('tab');
		$.post('/Index/dofav', {item_id:item_id, tab:tab}, function(result){
			putNotice(result.msg);
			if (result.status == 99) {
				$("#user"+tab+"list_"+item_id).hide();
			}
			putNotice(result.msg);
		}, 'json');
	});
	
	
	//发私信点开窗口动作
	$(".fasixin").click(function(){
		var sixinFromUid = $("#sixinFromUid").val();
		if (sixinFromUid == 0) {
			putNotice('登录后才可以发私信哦');
			jump(1, '/User/login?from=' + urlencode(window.document.location.pathname));
		} else {
			$(".sixinBox").slideDown(200);
		}
	});
	$(".sixinClose").click(function(){
		$(".sixinBox").slideUp(200);
	});
	
	//发私信发送动作
	$("#sendSixinBtn").click(function(){
		var ele = $(this);
		ele.attr('disabled', true);
		var local = ele.attr('local');
		if (local == '' || local == undefined) {
			local = 'global';
		}
		var sixinToUid = $("#sixinToUid").val();
		var sixinContent = $.trim($("#sixinContent").val());

		if (sixinContent == '') {
			putNotice('还没有填写私信内容呢');
			$("#sendSixinBtn").attr('disabled', false);
			return false;
		} else if (strlen(sixinContent) > 140) {
			putNotice('内容超出了规定长度');
			$("#sendSixinBtn").attr('disabled', false);
			return false;
		} else {
			$.post('/Index/sendsixin', {receiver_uid:sixinToUid, content:sixinContent, local:local}, function(result){
				if (result.status == 100) {
					$(".sixinBox").slideUp(200);
					$("#sixinContent").val('');
					if (result.data != '') {
						var sixin = result.data;
						$("#sixinList").prepend($(sixin).hide().fadeIn(1200));
					}
				} else if (result.status == 101) {
					jump(1, '/User/login?from=' + urlencode(window.document.location.pathname));
				}
				$("#sendSixinBtn").attr('disabled', false);
				putNotice(result.msg);
			}, 'json');
		}
	});
	
	//举报点开窗口
	$(".inform").click(function(){
		$(".informBox").slideDown(200);
	});
	$(".informClose").click(function(){
		$(".informBox").slideUp(200);
	});
	
	//举报动作
	$("#sendInformBtn").click(function(){
		var ele = $(this);
		ele.attr('disabled', true);
		var content = $.trim($("#informContent").val());
		var itemId = ele.attr('data');
		var tab = ele.attr('tab');

		if (content == '') {
			putNotice('还没有填写举报内容呢');
			$("#sendInformBtn").attr('disabled', false);
			return false;
		} else if (strlen(content) > 140) {
			putNotice('内容超出了140个字');
			$("#sendInformBtn").attr('disabled', false);
			return false;
		} else {
			$.post('/Index/doinform', {item_id:itemId, tab:tab, content:content}, function(result){
				if (result.status == 100) {
					$(".informBox").slideUp(200);
					$("#informContent").val('');
				}
				$("#sendInformBtn").attr('disabled', false);
				putNotice(result.msg);
			}, 'json');
		}
	});
	
	//举报评论动作
	$(".commentinformBtn").live('click', function(){
		var ele = $(this);
		if (ele.hasClass('disabled')) {
			return false;
		}
		ele.addClass('disabled');
		var itemId = ele.attr('data');

		$.post('/Index/docommentinform', {item_id:itemId}, function(result){
			putNotice(result.msg);
		}, 'json');
	});
	
	
	//私信详情页删除私信动作
	$(".sixinDeleteRowBtn").live('click', function(){
		var ele = $(this);
		var rowid = ele.attr('data');
		ele.hide();
		$.post('/User/delsixin', {row_id:rowid}, function(result){
			if (result.status == 100) {
				$("#sixinList_"+rowid).slideUp(200);
			} else {
				ele.show();
			}
			putNotice(result.msg);
		}, 'json');
	});
	
	//删除全部私信动作
	$(".sixinDeleteAllBtn").click(function(){
		var ele = $(this);
		var fid = ele.attr('data');
		ele.hide();
		$.post('/User/delallsixin', {fid:fid}, function(result){
			if (result.status == 100) {
				$("#sixinList").empty();
				$("#viewpaging").remove();
				$("#sixinFriendList_"+fid).slideUp(200);
			} else {
				ele.show();
			}
			putNotice(result.msg);
		}, 'json');
	});
	
	$("#sixinContent").keyup(function(){
		var content = $(this).val();
		var surplusLen = 140 - strlen(content);
		if (surplusLen < 0){
			surplusLen = 0;
		}
		$('#surplus').html(surplusLen);
	});
	
	//删除通知
	$(".delNoticeBtn").click(function(){
		var ele = $(this);
		var id = ele.attr('data');
		var tab = ele.attr('tab');
		
		ele.hide();
		$.post('/User/delnotice', {tabs:tab, id:id}, function(result){
			if (result.status == 100) {
				$("#noticeList_"+id).slideUp(200);
				if (parseInt(id) == 0) {
					$(".noticeList").hide();
				}
			} else {
				ele.show();
			}
			putNotice(result.msg);
		}, 'json');
	});
	
	//用户删除作品动作
	$(".deleteWBtn").click(function(){
		var ele = $(this);
		var item_id = ele.attr('data');
		var tab = ele.attr('tab');
		if (confirm('确定删除吗？')) {
			$.post('/User/deleteworks', {item_id:item_id, tab:tab}, function(result){
				if (result.status == 100) {
					$("#user"+tab+"list_"+item_id).hide();
				}
				putNotice(result.msg);
			}, 'json');
		}
	});
	
	//展开回复框动作
	$(".commentreplyshowBtn").live('click', function(){
		var item_id = $(this).attr('data');
		var fromUid = $(this).attr('fromUid');
		if (fromUid == 0) {
			putNotice('登录后才可以发表评论哦');
			jump(1, '/User/login?from=' + urlencode(window.document.location.pathname + "#commentlist"));
		} else {
			$("#commentreplytextarea_"+item_id).slideToggle(150);
		}
	});
	$(".commentreplyhideBtn").live('click', function(){
		var item_id = $(this).attr('data');
		$("#commentreplytextarea_"+item_id).slideUp(150);
	});
	
	//更多评论翻页
	$(".commentMore").live('click', function(){
		var ele = $(this);
		var item_id = ele.attr('data');
		var tab = ele.attr('tab');
		var p = ele.attr('p');
		
		if (ele.attr('disabled') == 'disabled') {
			return false;
		}
		
		ele.text('加载中……').attr('disabled', true);
		$.post('/Index/commentpage', {item_id:item_id, tab:tab, p:p}, function(result){
			if (result != '') {
				$("#commentlist").append(result);
				ele.parent().remove();
			}
		});
	});
	
	//发送评论动作
	$(".commentBtn").live('click', function(result){
		var ele = $(this);
		var item_id = ele.attr('data');
		var tab = ele.attr('tab');
		var parent_id = ele.attr('parent_id');
		var btnText = ele.text();
		var content = $("#textarea_"+parent_id).val();
		
		if (ele.attr('disabled') == 'disabled') {
			return false;
		}
		
		if ($.trim(content) == '') {
			putNotice('请填写评论内容');
			return false;
		}
		
		ele.text('提交中……').attr('disabled', true);
		$.post('/Index/docomment', {item_id:item_id, tab:tab, parent_id:parent_id, content:content}, function(result){
			if (result.status == 100) {
				$("#textarea_"+parent_id).val('');
				$("#commentreplytextarea_"+parent_id).slideUp(150);
				var comment = result.data;
				//$("html,body").animate({scrollTop: $("#commentlist").offset().top - 250}, 100);
				$("#commentlist").prepend($(comment).hide().fadeIn(1200));
				$("#comment_num").html(parseInt($("#comment_num").html()) + 1);
			}
			ele.text(btnText).attr('disabled', false);
			putNotice(result.msg);
		}, 'json');
	});
	
	//保存头像
	$("#avatarsettingBtn").click(function(){
		var ele = $(this);
		var avatar = $("#avatar_input").val();
		
		ele.val('保存中……').attr('disabled', true);
		$.post('/User/saveavatarsetting', {avatar:avatar}, function(result){
			if (result.status == 100) {
          	  	
          	    putNotice(result.msg);
			}
			ele.val('保存').attr('disabled', false);
		});
	});
	
	//保存密码
	$("#passwordsettingBtn").click(function(){
		var ele = $(this);
		var oldpassword = $("#oldpassword").val();
		var password = $("#password").val();
		var repassword = $("#repassword").val();
		
		ele.val('保存中……').attr('disabled', true);
		$.post('/User/savepasswordsetting', {oldpassword:oldpassword, password:password, repassword:repassword}, function(result){
			if (result.status == 100) {
				
			}
			putNotice(result.msg);
			ele.val('保存').attr('disabled', false);
		});
	});
	
	//保存二维码
	$("#qrcodesettingBtn").click(function(){
		var ele = $(this);
		var qrcode = $("#qrcode_input").val();
		var qrcodetype = $("#qrcodetype").val();
		
		ele.val('保存中……').attr('disabled', true);
		$.post('/User/saveqrcodesetting', {qrcode:qrcode, qrcodetype:qrcodetype}, function(result){
			if (result.status == 100) {
          	  	
          	    putNotice(result.msg);
			}
			ele.val('保存').attr('disabled', false);
		});
	});
	
});

//ajaxupload
function ajaxUpload(obj, fileType) {
	path = '';
	if (fileType == 'image') {
		$("#"+obj).show().find('img').attr('src', '/backend/images/admin_img/onLoad.gif').attr('width', '16');
	} else {
		path = "?savepath=file";
	}
	$.ajaxFileUpload({
	    url:"/User/uploadfile"+path, 
	    secureuri:false, 
	    fileElementId:obj+'_uploadInput', 
	    dataType:'json', 
	    success:function(result) { 
	  	    if(result.status == 100) {
	      	    var imgPath =  '/upload/' + result.data.file.savepath + result.data.file.savename
	      	    if (fileType == 'image') {
	      	    	$("#"+obj).show().find('img').attr('src', imgPath + '?' + Math.random()).attr('width', '140');
	                $("#"+obj+"_input").val(imgPath);
	                $("#"+obj+"_delBtn").show();
	      	    } else {
	      	    	$("#"+obj+"_filename").html('<i class="icon"></i>' + imgPath);
	                $("#"+obj+"_input").val(imgPath);
	                $("#"+obj+"_delBtn").show();
	      	    }
	  	    } else {
	  	        alert(result.msg);
	  	    }
	    }, 
  });
}

//deletefile
function deleteFile(obj, fileType){
	if (fileType == 'image') {
		$("#"+obj).hide();
		$("#"+obj).find('img').attr('src', '').attr('width', 0);
		$("#"+obj+"_input").val('');
	} else {
		$("#"+obj+"_filename").html('');
        $("#"+obj+"_input").val('');
        $("#"+obj+"_delBtn").hide();
	}
}

function putNotice(info)
{
	$(".directive_notif").slideDown(300).find('span').text(info);
	setTimeout(hideNotice, 3000);
}

function hideNotice()
{
	$(".directive_notif").slideUp(300);
}

//workssubmit
function worksSubmit() {
	var options = {
          url: '/User/saveworks',
          type: 'post',
          dataType: 'text',
          data: $("#worksform").serialize(),
          success: function (data) {
        	  var data = JSON.parse(data);
              if (data.status == 100) {
            	  putNotice(data.msg);
            	  jump(1, '/Works/view/id/' + data.data);
              } else {
            	  putNotice(data.msg);
            	  $("#workssubmit").attr('disabled', false).css("background", "").val('提交作品');
              }
          }
    };
	$("#workssubmit").attr('disabled', true).css("background", "#CCC").val('保存中……');
    $.ajax(options);
        
	return false;
} 

//articlesubmit
function articleSubmit() {
	var options = {
          url: '/User/savearticle',
          type: 'post',
          dataType: 'text',
          data: $("#articleform").serialize(),
          success: function (data) {
        	  var data = JSON.parse(data);
              if (data.status == 100) {
            	  putNotice(data.msg);
            	  jump(1, '/Article/view/id/' + data.data);
              } else {
            	  putNotice(data.msg);
            	  $("#articlesubmit").attr('disabled', false).css("background", "").val('发布文章');
              }
          }
    };
	$("#articlesubmit").attr('disabled', true).css("background", "#CCC").val('保存中……');
    $.ajax(options);
        
	return false;
} 

//materialsubmit
function materialSubmit() {
	var options = {
          url: '/User/savematerial',
          type: 'post',
          dataType: 'text',
          data: $("#materialform").serialize(),
          success: function (data) {
        	  var data = JSON.parse(data);
              if (data.status == 100) {
            	  putNotice(data.msg);
            	  jump(1, '/Material/view/id/' + data.data);
              } else {
            	  putNotice(data.msg);
            	  $("#materialsubmit").attr('disabled', false).css("background", "").val('发布素材');
              }
          }
    };
	$("#materialsubmit").attr('disabled', true).css("background", "#CCC").val('保存中……');
    $.ajax(options);
        
	return false;
} 

//admiresubmit
function admireSubmit() {
	var options = {
          url: '/User/saveadmire',
          type: 'post',
          dataType: 'text',
          data: $("#admireform").serialize(),
          success: function (data) {
        	  var data = JSON.parse(data);
              if (data.status == 100) {
            	  putNotice(data.msg);
            	  jump(1, '/Admire/view/id/' + data.data);
              } else {
            	  putNotice(data.msg);
            	  $("#admiresubmit").attr('disabled', false).css("background", "").val('发布欣赏');
              }
          }
    };
	$("#admiresubmit").attr('disabled', true).css("background", "#CCC").val('保存中……');
    $.ajax(options);
        
	return false;
} 

//userinfosubmit
function userinfoSubmit() {
	var options = {
          url: '/User/saveinfosetting',
          type: 'post',
          dataType: 'text',
          data: $("#infoform").serialize(),
          success: function (data) {
        	  var data = JSON.parse(data);
              if (data.status == 100) {
            	  putNotice(data.msg);
            	  $("#userinfosettingBtn").attr('disabled', false).css("background", "").val('保存');
              } else {
            	  putNotice(data.msg);
            	  $("#userinfosettingBtn").attr('disabled', false).css("background", "").val('保存');
              }
          }
    };
	$("#userinfosettingBtn").attr('disabled', true).css("background", "#CCC").val('保存中……');
    $.ajax(options);
        
	return false;
} 

//indexworkspage
function getIndexWorks(url, type, page)
{
	if (page == 0) {
		putNotice('~没有数据了~');
		return false;
	}
	//覆盖层代码
	
	
	$.post(url, {type:type, p:page}, function(result){
		if (result != '') {
			$("#indexWorksContainer").html(result);
		}
	});
}

//定时跳转
function jump(count, target) {    
    window.setTimeout(function(){    
        count--;    
        if(count > 0) {   
            jump(count, target);    
        } else {  
            location.href = target;    
        }    
    }, 1000);    
}


function urlencode(clearString) 
{
    var output = '';
    var x = 0;
     
    clearString = utf16to8(clearString.toString());
    var regex = /(^[a-zA-Z0-9-_.]*)/;
 
    while (x < clearString.length) 
    {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') 
        {
            output += match[1];
            x += match[1].length;
        } 
        else
        {
            if (clearString[x] == ' ')
                output += '+';
            else
            {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
            }
            x++;
        }
    }
 
    function utf16to8(str) 
    {
        var out, i, len, c;
 
        out = "";
        len = str.length;
        for(i = 0; i < len; i++) 
        {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) 
            {
                out += str.charAt(i);
            } 
            else if (c > 0x07FF) 
            {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } 
            else
            {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }
 
    return output;
}

//获取字符长度，中文2，英文1
function strlen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) { 
        var c = str.charCodeAt(i); 
       //单字节加1 
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
            len++; 
        } else { 
            len+=2; 
        } 
    } 
    return len;
}
